/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package  cool.taomu.toolkit.jsch.service

import com.google.inject.Inject
import com.jcraft.jsch.ChannelShell
import com.jcraft.jsch.Session
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.io.PrintWriter
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory

class Shell implements AutoCloseable {
	val static LOG = LoggerFactory.getLogger(Shell);

	var ChannelShell channel = null;
	Session session;
	IJschConnection ds;

	@Inject
	new(IJschConnection ds) {
		LOG.info("创建SHELL Channel");
		this.ds = ds;

	}

	def exec(String[] content) {
		return this.exec(content, "UTF-8")
	}

	def exec(String[] content, String charset) {
		this.session = ds.resource;
		this.channel = session.openChannel("shell") as ChannelShell;
		try(var pis = new PipedInputStream) {
			try(var pos = new PipedOutputStream) {
				try(var pw = new PrintWriter(pos)) {
					channel.inputStream = new PipedInputStream(pos);
					channel.outputStream = new PipedOutputStream(pis);
					channel.connect;
					for (it : content) {
						pw.println(it);
					}
					pw.flush();
					return IOUtils.toString(pis, charset);
				}
			}
		}
	}

	override close() throws Exception {
		if (channel !== null) {
			LOG.info("关闭SHELL Channel");
			channel.disconnect
			this.session.disconnect
		}
	}
}
